#!/bin/bash
BinDir=/var/lib/mysql
BinFile=/var/lib/mysql/binlog.index
BakDir=/home/shuaihu/mysqlbak
LogFile=/home/shuaihu/mysqlbak/backup.log
Week=`date +%w`
YMD=`date -d "-$Week day" +%Y%m%d`
NowYMD=`date +%Y%m%d`
NowTime=`date +%H:%M:%S`
FullBakDir=$BakDir/$YMD
PrevBakDir=`date -d '-5 week sunday' +%Y%m%d`
#删除过早的备份
if [ -d $BakDir/$PrevBakDir ]
then
    echo 删除四周前的备份:$PrevBakDir >>$LogFile
    rm -rf $BakDir/$PrevBakDir
fi
#如果文件夹不存在，创建文件夹并直接进行全备份
if [ ! -d $FullBakDir ]
then
    mkdir -p $FullBakDir
    BakType=full
elif [ $Week = '0' ]
then
    rm -rf $FullBakDir/*
    BakType=full
else
    BakType=increment
fi

if [ $BakType = 'full' ]
then
    echo "开始全备份-$NowYMD $NowTime" >>$LogFile
    mysqldump -uroot -R -E --quick --events --all-databases --flush-logs --delete-source-logs --single-transaction |gzip >$FullBakDir/$NowYMD.sql.gz
    echo $NowYMD 全备份成功！ >>$LogFile
else
    echo "开始增量备份-$NowYMD $NowTime" >>$LogFile
    mysqladmin -uroot flush-logs
    Counter=`wc -l $BinFile |awk '{print $1}'`
    NextNum=0
    for file in `cat $BinFile`
    do
        base=`basename $file`
        #basename用于截取mysql-bin.00000*文件名，去掉./mysql-bin.000005前面的./
        NextNum=`expr $NextNum + 1`
        if [ $NextNum -eq $Counter ]
        then
            echo $base 跳过! >> $LogFile
        else
            dest=$FullBakDir/$base
            echo $FullBakDir/$base >> $FullBakDir/$NowYMD
            if [ -f $dest ]
            then
                echo $base 已存在! >> $LogFile
            else
                cp $BinDir/$base $FullBakDir
                echo $base 复制完成 >> $LogFile
            fi
        fi
    done
    echo $NowYMD 增量备份成功! >> $LogFile
fi
echo "" >>$LogFile